package com.example.demo.controller;

// HelloController:  接收请求，返回响应

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.JwtUtils;
import com.example.demo.config.Result;
import com.example.demo.entity.User;
import com.example.demo.entity.dto.UserDto;
import com.example.demo.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@CrossOrigin
@RestController
@RequestMapping("/user")
@Tag(name = "用户管理")
public class UserController {

    @Autowired
    UserService userService;

    @Operation(summary = "根据条件查询用户（查询用户）")
    @GetMapping("/userPage")
    public Result userPage(@RequestParam(defaultValue ="1") Integer pageNum,
                           @RequestParam(defaultValue ="10") Integer pageSize,
                           @RequestParam(defaultValue ="") String search)
    {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(User::getName, search).orderByDesc(User::getCreateTime);
        Page<User> page = userService.page(new Page<User>(pageNum, pageSize), wrapper);
        return Result.ok(page);
    }

    @PostMapping("/saveUser")
    public Result saveUser(@RequestBody User user){
        user.setCreateTime(LocalDateTime.now());
        String password = "123Qq!!!";
        //把密码用密文形式进行保存
//        DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(password);
        user.setRole(0);
        user.setStatus(0);
        LocalDateTime createTime = LocalDateTime.now();
        user.setCreateTime(createTime);
        boolean save = userService.save(user);
        return Result.ok("新增用户成功！");
    }

    @GetMapping("/{id}")
    public Result saveUser(@PathVariable Long id){
        User one = userService.getById(id);
        return Result.ok(one);
    }

    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody User user){
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(User::getStatus,user.getStatus())
                .set(User::getName,user.getName())
                .set(User::getEmail,user.getEmail())
                .eq(User::getId,user.getId());
        boolean update = userService.update(updateWrapper);
        return Result.ok("修改用户信息成功！");
    }

    @PostMapping("/login")
    public Result lgoin(@RequestBody User user){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getName, user.getName()).eq(User::getPassword, user.getPassword());
        User one = userService.getOne(wrapper);
        if (one == null){
            return Result.fail(20001,"用户名或密码错误！");
        }else if(one.getStatus() == 1){
            return Result.fail(20001,"该用户已被禁言，请联系管理员！");
        }
        else{
            String token = JwtUtils.generateToken(one.getName());
            return Result.ok(one);
        }
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserDto user){
        System.out.println(user);
        if (StringUtils.isEmpty(user.getName()) || StringUtils.isEmpty(user.getEmail()) || StringUtils.isEmpty(user.getPassword()) || StringUtils.isEmpty(user.getCheckPass())){
            return Result.fail(200001,"请填写完毕之后再进行提交");
        }
        if (!user.getPassword().equals(user.getCheckPass())){
            return Result.fail(200001,"两次密码不一致，请重新输入");
        }

        if (user.getPassword().length()<8 || user.getPassword().length()>20){
            return Result.fail(200001,"密码格式错误");
        }
        User user1 = new User();
        BeanUtils.copyProperties(user,user1);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(User::getName, user1.getName());
        User one = userService.getOne(wrapper);
        if (one != null){
            return Result.fail(20001,"此用户用已被占用，请重新输入");
        }
        user1.setRole(0);
        user1.setStatus(0);
        LocalDateTime createTime = LocalDateTime.now();
        user.setCreateTime(createTime);
        userService.save(user1);
        return Result.ok("添加成功");
    }

    @PostMapping("/updateUserStatus")
    public Result updateUserStatus(@RequestBody User user){
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(User::getStatus,user.getStatus())
                .eq(User::getId,user.getId());
        boolean update = userService.update(updateWrapper);
        return Result.ok("修改用户状态成功！");
    }

    @PostMapping("/edit")
    public Result edit(@RequestBody UserDto user){
        if (StringUtils.isEmpty(user.getName()) || StringUtils.isEmpty(user.getEmail()) || StringUtils.isEmpty(user.getPassword()) || StringUtils.isEmpty(user.getCheckPass())){
            return Result.fail(200001,"请填写完毕之后再进行提交");
        }
        if (!user.getPassword().equals(user.getCheckPass())){
            return Result.fail(200001,"两次密码不一致，请重新输入");
        }

        if (user.getPassword().length()<8 || user.getPassword().length()>20){
            return Result.fail(200001,"密码格式错误");
        }
        User user1 = new User();
        BeanUtils.copyProperties(user,user1);
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.lambda()
                .set(User::getName,user.getName())
                .set(User::getEmail,user.getEmail())
                .set(User::getPassword,user.getPassword())
                .eq(User::getId,user.getId());
        User one = userService.getOne(wrapper);
        user1.setRole(0);
        user1.setStatus(0);
        LocalDateTime createTime = LocalDateTime.now();
        user.setCreateTime(createTime);
        userService.update(wrapper);
        return Result.ok("修改密码成功");
    }



}
